/* eslint-disable no-console */
// ============================== 导入依赖 ============================== //

import axios from 'axios'

let LOADING = null // 遮罩层
const QUEUE = [] // 异步队列

const SCRIPT = {} // 脚本状态
const CSS = {} // 样式状态

// ============================== 导出加载工具 ============================== //

export default {
  /**
   * 开始加载
   */
  loading() {
    QUEUE.push('')

    if (!LOADING) {
      LOADING = '加载时间'
      console.time(LOADING)
      console.log('开始加载', `${this.now().slice(11)}.${Date.now() % 1000}`)
    }
  },

  /**
   * 停止加载
   */
  unloading() {
    if (!QUEUE.length) return
    QUEUE.pop()

    setTimeout(() => {
      if (!QUEUE.length && LOADING) {
        console.log('停止加载', `${this.now().slice(11)}.${Date.now() % 1000}`)
        console.timeEnd(LOADING)
        LOADING = null
      }
    }, 100)
  },

  /**
   * 加载脚本
   */
  loadJS(src, name = '脚本') {
    const key = `${src}?${this.VERSION}`

    // 已加载过
    if (SCRIPT[key]) return Promise.resolve()

    return new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.type = 'text/javascript'
      script.src = key

      // 成功
      script.onload = () => {
        SCRIPT[key] = true
        resolve()
      }
      // 失败
      script.onerror = (err) => {
        const [TIP, msg] = [`${name}加载`, `${name}：加载失败`]
        this.logError(TIP, {}, err)
        this.MSG.error(msg)
        reject(new Error(msg))
      }

      // 添加到页面
      document.body.appendChild(script)
    })
  },

  /**
   * 加载样式
   */
  loadCSS(src, name = '样式') {
    const key = `${src}?${this.VERSION}`

    // 已加载过
    if (CSS[key]) return Promise.resolve()

    return new Promise((resolve, reject) => {
      const css = document.createElement('link')
      css.rel = 'stylesheet'
      css.href = key

      // 成功
      css.onload = () => {
        CSS[key] = true
        resolve()
      }
      // 失败
      css.onerror = (err) => {
        const [TIP, msg] = [`${name}加载`, `${name}：加载失败`]
        this.logError(TIP, {}, err)
        this.MSG.error(msg)
        reject(new Error(msg))
      }

      // 添加到页面
      document.head.appendChild(css)
    })
  },

  /**
   * 加载 JSON
   */
  async loadJSON(src) {
    const { data } = await axios.get(src)
    return this.json(data)
  },
}
